package cn.xiaobai.core.service;


import cn.xiaobai.core.domain.schedule.TaskExecutorProcessor;
import jakarta.annotation.Resource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Service;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;


/**
 * 工作调度服务
 *
 * @Author yangdaji
 * @Date 2023/12/11
 * @PackageName cn.xiaobai.core.service
 * @ClassName TaskExecuteService
 */
@Service
public class TaskExecuteService implements TaskExecutorProcessor {


    @Resource(name = "taskPoolScheduler")
    private ThreadPoolTaskScheduler taskPoolScheduler;

    @Resource(name = "workPoolScheduler")
    private ThreadPoolTaskExecutor workPoolScheduler;


    @Override
    public void startAsync(Runnable task) {
        this.workPoolScheduler.execute(task);
    }

    @Override
    public ScheduledFuture startPeriodly(Runnable task, long seconds) {
        long milliSeconds = seconds * 1000;
        return this.taskPoolScheduler.scheduleAtFixedRate(task, milliSeconds);
    }

    @Override
    public ScheduledFuture startPeriodlyMilliSeconds(Runnable task, long milliSeconds) {
        return this.taskPoolScheduler.scheduleAtFixedRate(task, milliSeconds);

    }

    @Override
    public void startExclusively(Runnable task, String taskName) {
        new Thread(task, taskName).start();
    }

    @Override
    public Future<?> startOnNewThread(Callable callable) {
        return taskPoolScheduler.submit(callable);
    }
}
